﻿using CIS.DB;
using CIS.Web.Common;
using CIS.Web.Models;
using CIS.Web.Properties;
using System;
using System.Data.Entity;
using System.IO;
using System.Linq;
using System.Linq.Dynamic;
using System.Net.Mail;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace CIS.Web.Controllers
{
	[RoutePrefix("MeetingContribute")]
	public class MeetingContributeController : BaseDbController
	{
		public ActionResult ShowPrivacy()
		{
			return View();
		}

		public ActionResult ShowPrivacyEN()
		{
			return View();
		}

		public async Task<ActionResult> Index(string conferenceId)
		{
			var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ID == conferenceId && x.Status == ConstValues.Status.正常);

			if (conferenceMaster == null)
			{
				return RedirectToAction(nameof(HomeController.MainIndex), nameof(HomeController).GetControllerName());
			}

			var model = new MeetingFormModel();
			model.ConferenceId = conferenceId;
			model.Introduction = conferenceMaster.Introduction == null ? string.Empty : conferenceMaster.Introduction;
			model.SubmitRequirement = conferenceMaster.SubmitRequirement == null ? string.Empty : conferenceMaster.SubmitRequirement.Replace("\r\n", string.Empty);
			model.Language = conferenceMaster.IsInternational ? ConstValues.Language.En : ConstValues.Language.Cn;

			var allowContribute = conferenceMaster.ContributeStartDate.Value <= DateTime.Now && conferenceMaster.ContributeEndDate.Value >= DateTime.Now ? true : false;
			if (allowContribute == false)
			{
				return View("SubmitClose", this.GetLoginModel());
			}

			var conferenceContributeForm = await DbContext.ConferenceContributeForm.AsNoTracking()
					.Where(x => x.Status == ConstValues.Status.正常 &&
						x.ConferenceId == conferenceId)
					.ToListAsync();
			model.TotalPage = conferenceContributeForm.Max(x => x.DisplayPage).Value;

			model.AwardsCount = DbContext.AwardsMaster.AsNoTracking()
					.Count(x => x.Status == ConstValues.Status.正常 &&
						x.ConferenceId == conferenceId);

			Session.Remove("TmpCode");

			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", conferenceId);

			ViewBag.ConferenceId = conferenceId;
			ViewBag.ConferenceName = conferenceMaster.ConferenceName;

			return View(model);
		}

		[Route("GetCurrentPageItem/{conferenceId}/{page:int}")]
		public async Task<JsonCamelCaseResult> GetCurrentPageItem(string conferenceId, int page)
		{
			var result = await DbContext.ConferenceContributeForm.AsNoTracking()
					.Where(x => x.Status == ConstValues.Status.正常 &&
						x.ConferenceId == conferenceId &&
						x.DisplayPage == page)
					.OrderBy(x => x.Sort)
					.ThenBy(x => x.DisplayName)
					.ToListAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(string.Empty, result)
						    , JsonRequestBehavior.AllowGet);
		}

		[Route("GetCurrentPageValue/{conferenceId}")]
		public async Task<JsonCamelCaseResult> GetCurrentPageValue(string conferenceId)
		{
			var code = Session["TmpCode"]?.ToString();

			var sqlResult = await DbContext.ConferenceContributeInfoTmp.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ID == code);

			if (sqlResult == null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(),
						JsonRequestBehavior.AllowGet);
			}

			var result = new
			{
				EssayTitle = sqlResult.EssayTitle,
				Keyword = sqlResult.Keyword,
				ProgramAbstract = sqlResult.ProgramAbstract,
				Abstract = sqlResult.Abstract,
				AbstractFile = Path.GetFileName(sqlResult.AbstractFile),
				SupplementaryFile = Path.GetFileName(sqlResult.SupplementaryFile),
				TopicId = sqlResult.TopicId,
				EssayId = sqlResult.EssayId,
				ReportId = sqlResult.ReportId,
				OcisId = sqlResult.OcisId,
				JournalId = sqlResult.JournalId
			};

			return JsonCamelCase(Utility.CreateSuccessJsonResult(string.Empty, result),
					JsonRequestBehavior.AllowGet);
		}

		[Route("GetPageViewValue/{conferenceId}")]
		public async Task<JsonCamelCaseResult> GetPageViewValue(string conferenceId)
		{
			var code = Session["TmpCode"]?.ToString();

			var sqlResult = await DbContext.ConferenceContributeInfoTmp.AsNoTracking()
					.FirstOrDefaultAsync(x => x.ID == code);

			if (sqlResult == null)
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(),
						JsonRequestBehavior.AllowGet);
			}

			var result = new
			{
				EssayTitle = sqlResult.EssayTitle,
				Keyword = sqlResult.Keyword,
				ProgramAbstract = sqlResult.ProgramAbstract.Replace("<p>", "").Replace("</p>", ""),
				Abstract = sqlResult.Abstract.Replace("<p>","").Replace("</p>",""),
				AbstractFile = Path.GetFileName(sqlResult.AbstractFile),
				SupplementaryFile = Path.GetFileName(sqlResult.SupplementaryFile),
				TopicId = string.IsNullOrEmpty(sqlResult.TopicId)? string.Empty :
						DbContext.TopicMaster.AsNoTracking().FirstOrDefault(x => x.ID == sqlResult.TopicId).TopicName,
				EssayId = string.IsNullOrEmpty(sqlResult.EssayId) ? string.Empty :
						DbContext.EssayMaster.AsNoTracking().FirstOrDefault(x => x.ID == sqlResult.EssayId).EssayType,
						
				ReportId = string.IsNullOrEmpty(sqlResult.ReportId) ? string.Empty :
						DbContext.ReportMaster.AsNoTracking().FirstOrDefault(x => x.ID == sqlResult.ReportId).ReportType,
						
				OcisId = string.IsNullOrEmpty(sqlResult.OcisId) ? string.Empty :
						DbContext.OCISMaster.AsNoTracking().FirstOrDefault(x => x.ID == sqlResult.OcisId).OCISName,
				JournalId = string.IsNullOrEmpty(sqlResult.JournalId) ? string.Empty :
						DbContext.JournalMaster.AsNoTracking().FirstOrDefault(x => x.ID == sqlResult.JournalId).JournalName,
						
			};

			return JsonCamelCase(Utility.CreateSuccessJsonResult(string.Empty, result),
					JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		[ValidateInput(false)]
		public async Task<JsonResult> CreateTmp(ConferenceContributeInfoModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			if (model.AbstractFile != null || model.SupplementaryFile != null)
			{
				var msg = await this.SaveFiles(model);
				if (!string.IsNullOrEmpty(msg))
				{
					return JsonCamelCase(Utility.CreateFailJsonResult(msg),
							JsonRequestBehavior.AllowGet);
				}
			}

			var code = Session["TmpCode"]?.ToString();

			if (string.IsNullOrEmpty(code))
			{
				code = Utility.GetTableId(ConstValues.TableName.ConferenceContributeInfo);
				var conferenceContributeInfo = new ConferenceContributeInfoTmp
				{
					ID = code,
					ConferenceId = model.ConferenceId,
					EssayTitle = model.EssayTitle?.Trim(),
					Keyword = model.Keyword?.Trim(),
					ProgramAbstract = model.ProgramAbstract == null ? string.Empty : model.ProgramAbstract.Trim(),
					Abstract = model.Abstract == null ? string.Empty : model.Abstract.Trim(),
					AbstractFile = model.AbstractFilePath,
					SupplementaryFile = model.SupplementaryFilePath,
					TopicId = model.Topic,
					EssayId = model.Essay,
					ReportId = model.Report,
					OcisId = model.Ocis,
					JournalId = model.Journal,
					ContributationStatus = ConstValues.ContributationStatus.待审,
					Sort = ConstValues.DefaultSort,
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = DateTime.Now
				};

				Session["TmpCode"] = code;

				DbContext.ConferenceContributeInfoTmp.Add(conferenceContributeInfo);
			}
			else
			{
				var result = await DbContext.ConferenceContributeInfoTmp
						.FirstOrDefaultAsync(x => x.ID == code);

				if (!(string.IsNullOrWhiteSpace(model.EssayTitle)) && result.EssayTitle != model.EssayTitle)
				{
					result.EssayTitle = model.EssayTitle.Trim();
				}
				if (!(string.IsNullOrWhiteSpace(model.Keyword)) && result.Keyword != model.Keyword)
				{
					result.Keyword = model.Keyword.Trim();
				}
				if (!(string.IsNullOrWhiteSpace(model.ProgramAbstract)) && result.ProgramAbstract != model.ProgramAbstract)
				{
					result.ProgramAbstract = model.ProgramAbstract.Trim();
				}
				if (!(string.IsNullOrWhiteSpace(model.Abstract)) && result.Abstract != model.Abstract)
				{
					result.Abstract = model.Abstract.Trim();
				}
				if (!(string.IsNullOrWhiteSpace(model.AbstractFilePath)) && result.AbstractFile != model.AbstractFilePath)
				{
					result.AbstractFile = model.AbstractFilePath;
				}
				if (!(string.IsNullOrWhiteSpace(model.SupplementaryFilePath)) && result.SupplementaryFile != model.SupplementaryFilePath)
				{
					result.SupplementaryFile = model.SupplementaryFilePath;
				}
				if (!(string.IsNullOrWhiteSpace(model.Topic)) && result.TopicId != model.Topic)
				{
					result.TopicId = model.Topic;
				}
				if (!(string.IsNullOrWhiteSpace(model.Essay)) && result.EssayId != model.Essay)
				{
					result.EssayId = model.Essay;
				}
				if (!(string.IsNullOrWhiteSpace(model.Report)) && result.ReportId != model.Report)
				{
					result.ReportId = model.Report;
				}
				if (!(string.IsNullOrWhiteSpace(model.Ocis)) && result.OcisId != model.Ocis)
				{
					result.OcisId = model.Ocis;
				}
				if (!(string.IsNullOrWhiteSpace(model.Journal)) && result.JournalId != model.Journal)
				{
					result.JournalId = model.Journal;
				}
			}

			await DbContext.SaveChangesAsync();

			return JsonCamelCase(Utility.CreateSuccessJsonResult(),
					JsonRequestBehavior.AllowGet);
		}

		[HttpPost]
		[ValidateAntiForgeryToken]
		public async Task<JsonResult> Submit(ConferenceContributeInfoModel model)
		{
			string controller = RouteData.Values["controller"].ToString();
			string actionName = RouteData.Values["action"].ToString();
			Utility.InsertLog(LoginUser, Request.Url.ToString(), controller, actionName, "Index", model.ConferenceId);

			var code = Session["TmpCode"]?.ToString();

			var infoTmp = await DbContext.ConferenceContributeInfoTmp
					.FirstOrDefaultAsync(x => x.ID == code);

			if (infoTmp != null && string.IsNullOrEmpty(infoTmp.EssayTitle))
			{
				return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgSubmissionMust),
						JsonRequestBehavior.AllowGet);
			}

			using (var transaction = DbContext.Database.BeginTransaction())
			{
				#region ConferenceContributeInfo
				var conferenceContributeInfo = new ConferenceContributeInfo
				{
					ID = Utility.GetNewContributeId(infoTmp.ConferenceId),
					ConferenceId = infoTmp.ConferenceId,
					EssayTitle = infoTmp.EssayTitle,
					Keyword = infoTmp.Keyword,
					ProgramAbstract = infoTmp.ProgramAbstract,
					Abstract = infoTmp.Abstract,
					AbstractFile = infoTmp.AbstractFile,
					SupplementaryFile = infoTmp.SupplementaryFile,
					TopicId = infoTmp.TopicId,
					EssayId = infoTmp.EssayId,
					ReportId = infoTmp.ReportId,
					OcisId = infoTmp.OcisId,
					JournalId = infoTmp.JournalId,
					HasSend = false,
					IsConfirm = false,
					ScheduleStatus = ConstValues.ScheduleStatus.无,
					ContributationStatus = ConstValues.ContributationStatus.待审,
					Sort = ConstValues.DefaultSort,
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = DateTime.Now
				};
				DbContext.ConferenceContributeInfo.Add(conferenceContributeInfo);
				DbContext.ConferenceContributeInfoTmp.Remove(infoTmp);
				#endregion

				#region AuthorInfo
				if (model.AuthorList != null)
				{
					var timeDiff = 0;
					foreach (var author in model.AuthorList)
					{
						var currentInfo = await DbContext.AuthorInfo.FirstOrDefaultAsync(x => x.ContributeId == conferenceContributeInfo.ID && x.Mail == author.Mail.Trim());
						if(currentInfo != null)
						{
							return JsonCamelCase(Utility.CreateFailJsonResult(Resources.MsgTheSameMail),
									JsonRequestBehavior.AllowGet);
						}

						var authorInfo = new AuthorInfo
						{
							ID = Utility.GetTableId(ConstValues.TableName.AuthorInfo),
							ConferenceId = model.ConferenceId,
							ContributeId = conferenceContributeInfo.ID,
							FamilyName = author.FamilyName?.Trim(),
							FirstName = author.FirstName?.Trim(),
							FullName = !string.IsNullOrEmpty(author.FullName) ? author.FullName?.Trim() :
									Utility.SetFullName(author.FamilyName?.Trim(), author.FirstName?.Trim(),
										Request.Cookies["_culture"] != null && Request.Cookies["_culture"].Value == ConstValues.Language.En ?
										ConstValues.Language.En : ConstValues.Language.Cn),
							Department = author.Department?.Trim(),
							Country = author.Country,
							State = author.State,
							City = author.City,
							Address = author.Address?.Trim(),
							ZipCode = author.ZipCode?.Trim(),
							Mobile = author.Mobile?.Trim(),
							Mail = author.Mail?.Trim(),
							CcMail = author.CcMail?.Trim(),
							IsFirstAuthor = false,
							IsContactAuthor = author.IsContactAuthor,
							IsPresenter = author.IsPresenter,
							SelfIntroduction = author.SelfIntroduction?.Trim(),
							Status = author.Status,
							Sort = author.Sort.HasValue ? author.Sort.Value : ConstValues.DefaultSort,
							Remark = author.Remark?.Trim(),
							Creator = LoginUser.UserName,
							CreateIP = LoginUser.IP,
							CreateDate = DateTime.Now.AddMilliseconds(timeDiff)
						};
						DbContext.AuthorInfo.Add(authorInfo);
						timeDiff += 50;

						author.ConferenceId = model.ConferenceId;
						author.ContributeId = conferenceContributeInfo.ID;
						await this.UpdateAffiliation(author);
					}
				}

				await DbContext.SaveChangesAsync();
				#endregion

				#region ProfileAwardsInfo
				if (!string.IsNullOrEmpty(model.AwardsList))
				{
					var awardsList = model.AwardsList.Split(ConstValues.chrSemicolon);
					foreach (var awards in awardsList)
					{
						if (!string.IsNullOrEmpty(awards))
						{
							var profileAwardsInfo = new ProfileAwardsInfo()
							{
								ID = Utility.GetTableId(ConstValues.TableName.ProfileAwardsInfo),
								UserName = LoginUser.UserName,
								ContributeId = conferenceContributeInfo.ID,
								AwardsId = awards,
								Creator = LoginUser.UserName,
								CreateIP = LoginUser.IP,
								CreateDate = DateTime.Now
							};

							DbContext.ProfileAwardsInfo.Add(profileAwardsInfo);
						}
					}
				}
				#endregion

				Session.Remove("TmpCode");

				#region SendMail
				if (model.AuthorList != null)
				{
					var conferenceMailServerMaster = await DbContext.ConferenceMailServerMaster.AsNoTracking()
							.FirstOrDefaultAsync(x => x.Status == ConstValues.Status.正常 &&
								x.MailType == ConstValues.MailType.投稿服务邮箱 &&
								x.ConferenceId == model.ConferenceId);

					if (conferenceMailServerMaster == null)
					{
						conferenceMailServerMaster = await DbContext.ConferenceMailServerMaster.AsNoTracking()
								.FirstOrDefaultAsync(x => x.Status == ConstValues.Status.正常 &&
									x.MailType == ConstValues.MailType.会议邮箱 &&
									x.ConferenceId == model.ConferenceId);
					}

					if (conferenceMailServerMaster != null)
					{
						var conferenceMaster = await DbContext.ConferenceMaster.AsNoTracking()
								.FirstOrDefaultAsync(x => x.ID == infoTmp.ConferenceId);

						var allAuthor = string.Join(conferenceMaster.IsInternational ? ConstValues.strComma : ConstValues.strCommaCn,
								model.AuthorList.OrderBy(x => x.Sort).ThenBy(x => x.FullName).Select(x => x.FullName));

						MailSender sender = new MailSender(conferenceMailServerMaster.MailServer);
						MailAddress from = new MailAddress(conferenceMailServerMaster.Mail);
						MailMessage message = Utility.GetMailContent(new MailModel
						{
							MailRemark = ConstValues.MailSubject.会议投稿,
							Language = conferenceMaster.IsInternational ? ConstValues.Language.En : ConstValues.Language.Cn,
							UserName = allAuthor,
							ConferenceId = conferenceMaster.ID,
							ConferenceName = conferenceMaster.ConferenceName,
							ConferenceNickName = conferenceMaster.ConferenceNickName,
							ContributeId = conferenceContributeInfo.ID,
							EssayTitle = conferenceContributeInfo.EssayTitle,
							Topic = DbContext.TopicMaster.AsNoTracking().FirstOrDefault(x => x.ID == conferenceContributeInfo.TopicId)?.TopicName,
							Essay = DbContext.EssayMaster.AsNoTracking().FirstOrDefault(x => x.ID == conferenceContributeInfo.EssayId)?.EssayType,
							Report = DbContext.ReportMaster.AsNoTracking().FirstOrDefault(x => x.ID == conferenceContributeInfo.ReportId)?.ReportType,
							Presenter = model.AuthorList.FirstOrDefault(x => x.IsPresenter)?.FullName
						});

						foreach (var author in model.AuthorList)
						{
							MailAddress to = new MailAddress(author.Mail);
							message.To.Add(to);

							if (!string.IsNullOrWhiteSpace(author.CcMail))
							{
								foreach (string cc in author.CcMail.Split(ConstValues.chrSemicolon))
								{
									if (!string.IsNullOrWhiteSpace(cc) && cc.Contains(ConstValues.chrAt))
									{
										message.CC.Add(new MailAddress(cc.Trim()));
									}
								}
							}

							if (!string.IsNullOrWhiteSpace(conferenceMailServerMaster.CcMail))
							{
								foreach (string cc in conferenceMailServerMaster.CcMail.Split(ConstValues.chrSemicolon))
								{
									if (!string.IsNullOrWhiteSpace(cc) && cc.Contains(ConstValues.chrAt))
									{
										message.Bcc.Add(new MailAddress(cc.Trim()));
									}
								}
							}
						}

						var mailTask = Task.Run(() =>
						{
							sender.SendMail(from, message, conferenceMailServerMaster.Password);
						});
					}
				}
				#endregion

				await DbContext.SaveChangesAsync();
				transaction.Commit();
			}

			return JsonCamelCase(Utility.CreateSuccessJsonResult(Resources.SuccessContribute),
					JsonRequestBehavior.AllowGet);
		}

		private async Task<string> SaveFiles(ConferenceContributeInfoModel model)
		{
			string nickName = DbContext.ConferenceMaster.AsNoTracking().FirstOrDefault(x => x.ID == model.ConferenceId)?.ConferenceNickName;
			string folder = Path.Combine(ConstValues.Uploads, nickName);
			string pfolder = Path.Combine(Server.MapPath(ConstValues.Uploads), nickName);

			var journalId = string.Empty;
			if (!string.IsNullOrEmpty(model.Journal))
			{
				var journalMaster = await DbContext.JournalMaster.AsNoTracking()
						.FirstOrDefaultAsync(x => x.ID == model.Journal &&
							x.ConferenceId == model.ConferenceId);
				journalId = journalMaster.JournalId;
				folder = Path.Combine(folder, journalMaster.JournalId);
			}

			if (!string.IsNullOrEmpty(journalId))
			{
				pfolder = Path.Combine(pfolder, journalId);
			}

			if (model.AbstractFile != null)
			{
				if (model.AbstractFile.ContentLength > ConstValues.FileMaxLength)
				{
					return Resources.MsgFileOverflowError;
				}
				
				string fileName = nickName + ConstValues.strHyphen +
						Path.GetExtension(model.AbstractFile.FileName).Replace(".", "").ToUpper() + ConstValues.strHyphen +
						DateTime.Now.ToString("yyyy") + ConstValues.strHyphen +
						Utility.GetRandom() + Path.GetExtension(model.AbstractFile.FileName);
				model.AbstractFilePath = Path.Combine(folder, fileName);
				var saveFileTask = Task.Run(() =>
				{
					string pFullPath = Path.Combine(pfolder, fileName);
					if (!Directory.Exists(pfolder))
					{
						Directory.CreateDirectory(pfolder);
					}
					model.AbstractFile.SaveAs(pFullPath);
				});
				Task.WaitAll(saveFileTask);
			}

			if (model.SupplementaryFile != null)
			{
				if (model.SupplementaryFile.ContentLength > ConstValues.FileMaxLength)
				{
					return Resources.MsgFileOverflowError;
				}
				
				string fileName = nickName + ConstValues.strHyphen +
						Path.GetExtension(model.SupplementaryFile.FileName).Replace(".", "").ToUpper() + ConstValues.strHyphen +
						DateTime.Now.ToString("yyyy") + ConstValues.strHyphen +
						Utility.GetRandom() + Path.GetExtension(model.SupplementaryFile.FileName);
				model.SupplementaryFilePath = Path.Combine(folder, fileName);
				var saveFileTask = Task.Run(() =>
				{
					string pFullPath = Path.Combine(pfolder, fileName);
					if (!Directory.Exists(pfolder))
					{
						Directory.CreateDirectory(pfolder);
					}
					model.SupplementaryFile.SaveAs(pFullPath);
				});
				Task.WaitAll(saveFileTask);
			}
			return string.Empty;
		}

		public ActionResult SubmitClose()
		{
			return View(this.GetLoginModel());
		}

		public LoginViewModel GetLoginModel()
		{
			string userName = Session["userName"]?.ToString();
			string password = Session["password"]?.ToString();
			string validateCode = Session["ValidateCode"]?.ToString();

			var model = new LoginViewModel();

			model.AccountName = userName;
			model.Password = password;
			model.ValidateCode = validateCode;

			return model;
		}

		private async Task UpdateAffiliation(AuthorModel model)
		{
			var affiliationList = await DbContext.AffiliationInfo
					.Where(x => x.ConferenceId == model.ConferenceId &&
						x.ContributeId == model.ContributeId &&
						x.Mail == model.Mail)
					.ToListAsync();

			DbContext.AffiliationInfo.RemoveRange(affiliationList);

			var dt = DateTime.Now;

			#region 单位0
			if (!string.IsNullOrEmpty(model.Affiliation0))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation0?.Trim(),
					Country = model.Country0,
					Status = model.Status,
					Sort = 0,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位1
			if (!string.IsNullOrEmpty(model.Affiliation1))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation1?.Trim(),
					Country = model.Country1,
					Status = model.Status,
					Sort = 1,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位2
			if (!string.IsNullOrEmpty(model.Affiliation2))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation2?.Trim(),
					Country = model.Country2,
					Status = model.Status,
					Sort = 2,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位3
			if (!string.IsNullOrEmpty(model.Affiliation3))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation3?.Trim(),
					Country = model.Country3,
					Status = model.Status,
					Sort = 3,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位4
			if (!string.IsNullOrEmpty(model.Affiliation4))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation4?.Trim(),
					Country = model.Country4,
					Status = model.Status,
					Sort = 4,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位5
			if (!string.IsNullOrEmpty(model.Affiliation5))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation5?.Trim(),
					Country = model.Country5,
					Status = model.Status,
					Sort = 5,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位6
			if (!string.IsNullOrEmpty(model.Affiliation6))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation6?.Trim(),
					Country = model.Country6,
					Status = model.Status,
					Sort = 6,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位7
			if (!string.IsNullOrEmpty(model.Affiliation7))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation7?.Trim(),
					Country = model.Country7,
					Status = model.Status,
					Sort = 7,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位8
			if (!string.IsNullOrEmpty(model.Affiliation8))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation8?.Trim(),
					Country = model.Country8,
					Status = model.Status,
					Sort = 8,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
			#region 单位9
			if (!string.IsNullOrEmpty(model.Affiliation9))
			{
				var affiliationInfo = new AffiliationInfo
				{
					ID = Utility.GetTableId(ConstValues.TableName.AffiliationInfo),
					ConferenceId = model.ConferenceId,
					ContributeId = model.ContributeId,
					Mail = model.Mail?.Trim(),
					Affiliation = model.Affiliation9?.Trim(),
					Country = model.Country9,
					Status = model.Status,
					Sort = 9,
					Remark = model.Remark?.Trim(),
					Creator = LoginUser.UserName,
					CreateIP = LoginUser.IP,
					CreateDate = dt
				};
				DbContext.AffiliationInfo.Add(affiliationInfo);
			}
			#endregion
		}
	}
}